import os
import sys
import json
import queue
import shutil
import asyncio
import aiohttp
import requests
import argparse
from fake_useragent import UserAgent

parser = argparse.ArgumentParser(description='视频下载器目前仅支持 .m3u8文件')

# 视频url
parser.add_argument("-d", "--dir", type=str, default=None, help="download video dir; 视频下载文件夹")
# 输出文件
parser.add_argument("-f", "--file", type=str, default=None, help="m3u8 url file; 存放.m3u8链接文件 格式: 视频名,m3u8链接\\n")
# 脚本参数
args = parser.parse_args()

ua = UserAgent()

header = {
    'User-Agent': ua.random,
    'Accept': '*/*',
    'Accept-language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'sec-ch-ua-mobile': '?0',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'cross-site',
}


# 处理请求头
def handle_headers(url):
    # 芒果tv
    if 'mgtv.com' in url:
        header['Origin'] = 'https://www.mgtv.com'
        header['Referer'] = 'https://www.mgtv.com'
    # 腾讯视频
    elif 'tc.qq.com' in url:
        header['Origin'] = 'https://v.qq.com'
        header['Referer'] = 'https://v.qq.com'
    # 优酷视频
    elif 'cibntv.net' in url:
        header['Origin'] = 'https://v.youku.com'
    # 爱奇艺
    elif 'iqiyi.com' in url:
        header['Origin'] = 'https://www.iqiyi.com'
    return header

# 处理爱奇艺链接
def handle_aqiyi_m3u8(content):
    data = json.loads(content).get('data').get('program').get('video')[0].get('m3u8')
    print(f'data: {data}')


def request(url):
    response = requests.get(url=url, headers=header)
    handle_aqiyi_m3u8(response.content.decode('utf-8'))


url = 'https://cache.video.iqiyi.com/dash?tvid=339770500&bid=600&vid=b4211de97fa9593a620b4505e4b41cc3&src=01010031010000000000&vt=0&rs=1&uid=1716828128&ori=pcw&ps=1&k_uid=eefa3f8c290815ae86654dcfbd1c15eb&pt=0&d=0&s=&lid=0&cf=0&ct=0&authKey=e175701c12dabfda14f25e5c3bd37ac6&k_tag=1&dfp=a10b2f52ac0372457fb46d1bf3225e55db8876741309a8214d1b073645a0dd3f97&locale=zh_cn&pck=d7R9K4XOhYphLTKykRu5GDMAqtAETm1U7m25C9m1gCxRm3gCsQf24dCg0oBe5i9USi4z3F88&k_err_retries=0&up=&sr=1&qd_v=5&tm=1695869927839&qdy=u&qds=0&k_ft1=706436220846084&k_ft4=1162321298202628&k_ft2=262335&k_ft5=134217729&k_ft6=128&k_ft7=687865860&fr_300=120_120_120_120_120_120&fr_500=120_120_120_120_120_120&fr_600=120_120_120_120_120_120&fr_800=120_120_120_120_120_120&fr_1020=120_120_120_120_120_120&bop=%7B%22version%22%3A%2210.0%22%2C%22dfp%22%3A%22a10b2f52ac0372457fb46d1bf3225e55db8876741309a8214d1b073645a0dd3f97%22%2C%22b_ft1%22%3A8%7D&ut=1&vf=09da4808fcd49693579f00d445321ecd'
request(url)